<!-- #layout name=blank-->
<div id="app" v-cloak>
  <div class="page-header">
    <h1 class="title">Code</h1>
  </div>
  <kb-breadcrumb :breads="breads"></kb-breadcrumb>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a
        class="btn green navbar-btn"
        :href="codeCreateUrl"
        v-show="currentTab!== 'all'"
        >{{ createBtnText }}</a
      >
      <div class="btn-group navbar-btn" v-show="currentTab == 'all'">
        <button
          class="btn green dropdown-toggle"
          type="button"
          data-toggle="dropdown"
          ><span>Create</span> <i class="fa fa-angle-down"></i
        ></button>
        <ul class="dropdown-menu" role="menu">
          <template v-for="(item,index) in codeTypes">
            <li :key="index" v-if="item.editUrl">
              <a :href="item.editUrl">{{ item.displayName }}</a>
            </li>
          </template>
        </ul>
      </div>
      <a
        v-show="['api','all'].indexOf(currentTab) > -1"
        @click="showApiModal=true"
        class="btn navbar-btn green"
        >API Generator</a
      >
      <a class="btn navbar-btn green" @click="onDebug">Debug</a>
      <a
        v-show="selectedRows.length"
        @click="onDelete"
        class="btn red navbar-btn"
        >Delete</a
      >
    </div>
  </div>
  <ul class="nav nav-tabs">
    <li
      v-for="item in codeTypes"
      :key="item.value"
      :class="{active:item.value==currentTab}"
    >
      <a href="javascript:;" @click="onTabClick(item.value)"
        >{{ item.displayName }}</a
      >
    </li>
  </ul>
  <table class="table tree table-hover">
    <thead>
      <tr>
        <th>
          <div class="tree-checkbox">
            <input
              type="checkbox"
              :disabled="model.length==0"
              @click="selectedAll"
              :checked="allRows.length == selectedRows.length && allRows.length > 0"
            />
            {{Kooboo.text.common.name}}
          </div>
        </th>
        <th>{{Kooboo.text.site.code.codeType}}</th>
        <th>{{Kooboo.text.common.usedBy}}</th>
        <th>{{Kooboo.text.common.preview}}</th>
        <th>{{Kooboo.text.common.lastModified}}</th>
        <th>
          <div class="tree-ctrl-bar">
            <a class="btn btn-xs" @click="expandAll">expandAll</a>
            <a class="btn btn-xs" @click="collapseAll">collapseAll</a>
          </div>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="row in model" :key="row.id" :class="row.__class">
        <template v-if="row.directory">
          <td colspan="100">{{row.directory}}</td>
        </template>
        <template v-else>
          <td @click="selectRow(row)">
            <div class="tree-checkbox">
              <input type="checkbox" :checked="selectedRows.indexOf(row)>-1" />
              {{row.name}}
            </div>
          </td>
          <td>
            <span class="label label-sm label-success">
              {{ row.codeType }}
            </span>
          </td>
          <td>
            <a
              class="label label-sm kb-table-label-refer"
              :style="{
                                background: Kooboo.getLabelColor(item.key.toLowerCase())
                              }"
              v-for="(item, index) in Kooboo.objToArr(row.references)"
              :key="index"
              @click.stop="onShowRelationModal(item.key, row.id, Kooboo.Code.name)"
            >
              {{ item.value + " " +
              Kooboo.text.component.table[item.key.toLowerCase()] }}
            </a>
          </td>
          <td>
            <a :href="row.previewUrl" target="_blank"> {{ row.previewUrl }} </a>
          </td>
          <td>
            <span>
              {{ new Date(row.lastModified).toDefaultLangString() }}
            </span>
          </td>
          <td :style="{width: '200px', textAlign: 'right'}">
            <a class="btn btn-sm blue" :href="getEditUrl(row)" @click.stop>
              {{ Kooboo.text.common.edit }}
            </a>
          </td>
        </template>
      </tr>
    </tbody>
  </table>
  <kb-relation-modal></kb-relation-modal>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showApiModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button class="close" data-dismiss="modal"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">API Generation</h4>
        </div>
        <div class="modal-body" v-if="showApiModal">
          <div style="overflow: hidden">
            <div class="row" style="min-width: 600px">
              <div class="wizard">
                <div class="wrapper">
                  <span
                    v-for="(item,index) in steps"
                    :class="{active:index==currentStepIndex}"
                    >{{ item }}<b></b
                  ></span>
                </div>
              </div>
            </div>
          </div>

          <div v-show="currentStepIndex==0">
            <table class="table table-hover">
              <tbody>
                <template v-for="(type,index) in types">
                  <tr :key="index">
                    <td>
                      <span class="table-tree-indent"></span>
                      <span class="table-tree-toggle"
                        ><i class="fa fa-caret-down"></i
                      ></span>
                      <a href="javascript:;">{{ type.displayName }}</a>
                    </td>
                    <td></td>
                  </tr>
                  <tr
                    v-for="(item,i) in type.items"
                    @click="item.selected=!item.selected"
                    :key="index+'_'+i"
                  >
                    <td>
                      <span
                        class="table-tree-indent"
                        style="width: 22px"
                      ></span>
                      <input type="checkbox" v-model="item.selected" />
                      <a href="javascript:;">{{ item.name }}</a>
                    </td>
                    <td></td>
                  </tr>
                </template>
              </tbody>
            </table>
          </div>
          <div v-show="currentStepIndex==1">
            <div class="row">
              <template v-for="(type,index) in types">
                <template v-for="(item,i) in type.items">
                  <div
                    class="col-sm-12 col-md-4"
                    v-if="item.selected"
                    :key="index+'-'+i"
                  >
                    <div class="thumbnail">
                      <div class="caption">
                        <h3>{{ item.name }}</h3>
                        <div>
                          <div
                            class="form-group"
                            v-for="(action,aIndex) in item.actions"
                          >
                            <div class="checkbox">
                              <label>
                                <input
                                  type="checkbox"
                                  v-model="action.selected"
                                />
                                {{ action.type }}
                              </label>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </template>
            </div>
          </div>
          <div v-show="currentStepIndex==2">
            <template v-for="(type,index) in types">
              <template v-for="(item,i) in type.items">
                <div class="media" v-if="item.selected" :key="index+'-'+i">
                  <div class="media-body">
                    <h4 class="media-heading">{{ item.name }}</h4>
                    <p
                      >{{item.actions.filter(function(act){ return act.selected
                      }).map(function(act){return act.type }).join(' / ')}}</p
                    >
                  </div>
                </div>
              </template>
            </template>
          </div>
        </div>
        <div class="modal-footer">
          <button
            class="btn green"
            v-if="currentStepIndex==1||currentStepIndex==2"
            @click="currentStepIndex--"
            >{{ Kooboo.text.common.previous }}</button
          >
          <button
            class="btn green"
            v-if="currentStepIndex==0||currentStepIndex==1"
            @click="currentStepIndex++"
            >{{ Kooboo.text.common.next }}</button
          >
          <button class="btn blue" v-if="currentStepIndex==2" @click="onConfirm"
            >{{ Kooboo.text.common.save }}</button
          >
        </div>
      </div>
    </div>
  </div>
</div>
<style>
  .tree-checkbox {
    display: contents;
    margin-left: 10px;
  }
  .tree-checkbox input {
    vertical-align: middle;
    margin-right: 5px;
    margin-top: -2px;
  }
  .tree-ctrl-bar {
    text-align: right;
  }
</style>

<script>
  Kooboo.loadJS([
    "/_Admin/Scripts/components/kbBreadcrumb.js",
    "/_Admin/Scripts/components/kbTable.js",
    "/_Admin/Scripts/components/kbRelationModal.js",
    "/_Admin/Scripts/lib/treegrid/jquery.treegrid.min.js",
  ]);

  new Vue({
    el: "#app",
    data: function () {
      return {
        breads: [
          {
            name: "SITES",
          },
          {
            name: "DASHBOARD",
          },
          {
            name: Kooboo.text.common.Code,
          },
        ],
        currentTab: "all",
        codeTypes: [],
        showApiModal: false,
        selectedRows: [],
        model: [],
        currentStepIndex: 0,
        steps: [
          Kooboo.text.common.chooseObject,
          Kooboo.text.common.chooseAction,
          Kooboo.text.common.confirm,
        ],
        types: [],
      };
    },
    mounted: function () {
      var me = this;
      Kooboo.Code.getCodeType().then(function (res) {
        if (res.success) {
          var types = Kooboo.objToArr(res.model, "value", "displayName");
          types = _.orderBy(types, [
            function (o) {
              return o.value;
            },
          ]);
          types.forEach(function (type) {
            type.editUrl = Kooboo.Route.Get(Kooboo.Route.Code.EditPage, {
              codeType: type.value,
            });
          });
          types.splice(0, 0, {
            displayName: Kooboo.text.common.all,
            value: "all",
          });
          me.codeTypes = types;
          me.onTabClick(me.currentTab);
        }
      });
    },
    computed: {
      codeCreateUrl: function () {
        return Kooboo.Route.Get(
          Kooboo.Route.Code.EditPage,
          this.currentTab !== "all"
            ? {
                codeType: this.currentTab,
              }
            : null
        );
      },
      createBtnText: function () {
        var me = this;
        var result = Kooboo.text.common.create + " ";
        var type = me.codeTypes.find(function (f) {
          return f.value == me.currentTab;
        });
        if (type) result += type.displayName;
        return result;
      },
      allRows: function () {
        return this.model.filter(function (f) {
          return f.directory === undefined;
        });
      },
    },
    methods: {
      onDelete: function () {
        var me = this;
        var haveRelations = this.selectedRows.some(function (s) {
          return s.relations && Object.keys(s.relations).length;
        });

        var confirmStr = haveRelations
          ? Kooboo.text.confirm.deleteItemsWithRef
          : Kooboo.text.confirm.deleteItems;

        var ids = this.selectedRows.map(function (m) {
          return m.id;
        });

        if (!confirm(confirmStr)) return;
        Kooboo[Kooboo.Code.name]
          .Deletes({
            ids: ids,
          })
          .then(function (res) {
            if (res.success) {
              me.onTabClick(me.currentTab);
              window.info.done(Kooboo.text.info.delete.success);
            } else {
              window.info.done(Kooboo.text.info.delete.fail);
            }
          });
      },
      onTabClick: function (type) {
        var me = this;
        Kooboo.Code.getListByType({
          codeType: type,
        }).then(function (res) {
          if (res.success) {
            me.model = treeGrid(res.model);
            me.currentTab = type;
            me.selectedRows = [];
            me.$nextTick(function () {
              $(".tree").treegrid({
                expanderExpandedClass: "fa fa-caret-down",
                expanderCollapsedClass: "fa fa-caret-right",
                initialState: "collapsed",
              });
            });
          }
        });
      },
      onShowRelationModal: function (by, id, type) {
        Kooboo.EventBus.publish("kb/relation/modal/show", {
          by: by,
          type: type,
          id: id,
        });
      },
      getEditUrl: function (item) {
        return Kooboo.Route.Get(Kooboo.Route.Code.EditPage, {
          id: item.id,
          codeType: item.codeType,
        });
      },
      getDebugUrl: function (id) {
        return Kooboo.Route.Get(Kooboo.Route.Code.DebugPage, {
          id: id,
        });
      },
      onConfirm: function () {
        var list = [];
        var me = this;
        me.types.forEach(function (type) {
          type.items.forEach(function (item) {
            if (item.selected) {
              var model = {
                type: type.name,
                name: item.name,
                actions: item.actions
                  .filter(function (action) {
                    return action.selected;
                  })
                  .map(function (action) {
                    return action.type;
                  }),
              };

              model.actions.length && list.push(model);
            }
          });
        });

        Kooboo.APIGeneration.Generate({
          updateModel: list,
        }).then(function (res) {
          if (res.success) {
            window.info.done("Generate successful");
            me.showApiModal = false;
            me.onTabClick(me.currentTab);
          }
        });
      },
      selectedAll: function () {
        if (this.allRows.length == this.selectedRows.length) {
          this.selectedRows = [];
        } else {
          this.selectedRows = this.allRows;
        }
      },
      selectRow: function (item) {
        var arr = this.selectedRows.filter(function (i) {
          return i == item;
        })[0];

        if (arr) {
          this.selectedRows = this.selectedRows.filter(function (i) {
            return i != item;
          });
        } else {
          this.selectedRows.push(item);
        }
      },
      expandAll: function () {
        $(".tree").treegrid("expandAll");
      },
      collapseAll: function () {
        $(".tree").treegrid("collapseAll");
      },
      onDebug: function () {
        window.location.href =
          "KScript/CodeDebugger.html?SiteId=" + Kooboo.getQueryString("SiteId");
      },
    },
    watch: {
      showApiModal: function () {
        var me = this;
        Kooboo.APIGeneration.getObjects().then(function (res) {
          if (res.success) {
            var list = _.groupBy(res.model, "type");
            me.types = Kooboo.objToArr(list).map(function (data) {
              return {
                name: data.key,
                displayName: data.value.length
                  ? data.value[0].typeDisplayName
                  : data.key,
                items: data.value.map(function (item) {
                  item.selected = false;
                  item.actions = item.actions.map(function (action) {
                    return {
                      selected: false,
                      type: action,
                    };
                  });
                  return item;
                }),
              };
            });
          }
        });
      },
    },
  });

  function treeGrid(model) {
    var a = document.createElement("a");
    function createNode(name) {
      return {
        name: name,
        directories: [],
        files: [],
      };
    }

    var tree = createNode("root");

    for (var i = 0; i < model.length; i++) {
      var item = model[i];
      var previewUrl = item.previewUrl;
      if (!previewUrl) {
        tree.files.push(item);
      } else {
        a.href = previewUrl;
        var paths = a.pathname.split("/").filter(function (f) {
          return f;
        });
        insertIntoNode(paths, item, tree);
      }
    }

    function insertIntoNode(paths, item, node) {
      if (paths.length <= 1) {
        node.files.push(item);
      } else {
        var dirname = paths.shift();
        var dir = node.directories.filter(function (f) {
          return f.name == dirname;
        })[0];
        if (!dir) {
          dir = createNode(dirname);
          node.directories.push(dir);
        }
        insertIntoNode(paths, item, dir);
      }
    }

    var result = [];

    function buildResult(node, parent) {
      for (var i = 0; i < node.directories.length; i++) {
        var dirNode = node.directories[i];
        var dir = { directory: dirNode.name };
        dir.__class = [];
        var id = parent + "split" + dirNode.name;
        dir.__class.push("treegrid-" + id);
        if (parent) {
          dir.__class.push("treegrid-parent-" + parent);
        }
        result.push(dir);
        buildResult(dirNode, id);
      }

      for (var j = 0; j < node.files.length; j++) {
        var file = node.files[j];
        file.__class = [];
        if (parent) {
          file.__class.push("treegrid-parent-" + parent);
        }
        result.push(file);
      }
    }

    buildResult(tree, "");

    return result;
  }
</script>
